'''
Author: Mr.Sen
LastEditTime: 2021-02-16 20:45:11
Description: 分发数据
Website: https://grimoire.cn
Copyright (c) Mr.Sen All rights reserved.
'''
from django.http import Http404
from database.models import *
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required


def JsonResponseOk(dic={}):
    okDic = {
        "msg":"",
        "status":1
    }
    okDic.update(dic)
    return JsonResponse(okDic)


def JsonResponseFail(dic={}):
    okDic = {
        "msg":"",
        "status":0
    }
    # dic.update(okDic)
    okDic.update(dic)
    return JsonResponse(okDic)


'''
    url = /user-info/
    GET
    私有类
    用于返回当前用户登陆信息
'''
@login_required(login_url='/login/')
def userInfo(requests):
    user = users.objects.get(id=requests.user.id)
    # iconsString = "iconfont-small@https://grimoire.cn"
    icons = user.icons.split("\n")
    while "" in icons:
        icons.remove("")
    iconList = []
    for i in icons:
        key, value = i.split("@")
        iconList.append({"icon": key, "url":value})
    default = {
        "nickName": user.nicName,
        "avatar": user.avatar,
        "iconList": iconList
    }
    return JsonResponse(default)


'''
    url = "/renderEditor/?edit="
    这个函数是用来返回渲染编辑器的数据
    content 和 title 两个参数必须
    同时需要校验拥有这个接口的访问权限

'''
@login_required(login_url="/login/")
def RenderEditor(request):  # 编辑器预置内容
    docId = request.GET.get("edit", "0")
    # print("worked", docId)
    # 传入了错误的参数
    if not docId.isdigit():
        ret = {"content": ""}
        # print("worked 2")
        return JsonResponseFail(ret)

    content = contents.objects.filter(id=int(docId)).first()

    # 没有找到文章
    if content == None:
        ret = {"content": ""}
        return JsonResponseFail(ret)

    # 未拥有编辑权限
    if content.authorId != request.user.id:
        raise Http404()

    ret = {"content": "# " + content.title + "\n\r" + content.rawtext, "title": content.title}
    # print(ret)
    return JsonResponseOk(ret)



'''
    url="/metaOfUser/"
    获取用于渲染首页下的用户拥有分类
'''
@login_required(login_url='/login/')
def DataForGroup(request):  # 获取用户拥有的分类数据
   
    data = meta.objects.filter(user__id=str(request.user.id)).values_list("name", "count", "id", "lastEdit")
    # data = meta.objects.filter(belongTo=request.user.id).values_list("name", "count", "id", "lastEdit")
    print(data)
    # return JsonResponse({"hello":"world"})
    # dic = {"status": 1 if (data is not None) else 0, "msg": "获取分类成功"}
    if data is None: return JsonResponseFail()
    dic = {} 
    lst = []
    for i, j, x, y in data:
        lst.append({
            "name": i,
            "count": j,
            "id": x,
            "lastEdit": y,
        })
    dic["lst"] = lst
    return JsonResponse(dic)



'''
    url = "/docOfMeta/
    需要返回一个title, id和 text（文章缩略信息）
    获取分类下文章的数据
'''
@login_required(login_url="/login/")
def RenderMeta(request):
    
    metaId = request.GET.get("meta", "0")
    if not metaId.isdigit():
        return JsonResponseFail()

    content = contents.objects.filter(meta__id=int(metaId))
    if content.first() is None:
        return JsonResponseFail()

    if content[0].authorId != request.user.id:
        return JsonResponseFail()

    ret = []
    for i in content:
        text = (i.rawtext[0:60] if len(i.rawtext) >= 60 else i.rawtext).replace("\n", "")
        ret.append({
            "id": i.id, 
            "title": i.title,
            "text": text, 
            "lastEdit": i.created, 
            "length": len(i.rawtext)
        })

    return JsonResponseOk({"data": ret})


'''
    获取用户配置信息
    url = "/user-info/'
    GET
'''
@login_required(login_url="/login/")
def getUserInfo(request):
    config = users.objects.get(request.user.id)
    ret = {
        "iconfont":config.iconfont,
        "icons":config.icons,
        "username":config.nicName,
        "avatar":config.avatar,
    }
    return JsonResponseOk({"data":ret})